package com.jieshuibao.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.Advisory;
import com.jieshuibao.model.db.AdvisoryExample;
import com.jieshuibao.model.db.AdvisoryExample.Criteria;
import com.jieshuibao.model.db.AdvisoryRecording;
import com.jieshuibao.model.db.AdvisoryRecordingExample;
import com.jieshuibao.model.db.AdvisoryUser;
import com.jieshuibao.model.db.AdvisoryUserExample;
import com.jieshuibao.model.db.Counselor;
import com.jieshuibao.model.db.Duty;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.domain.AdvisoryRecordingUser;
import com.jieshuibao.model.domain.AdvisoryRequest;
import com.jieshuibao.model.domain.AdvisoryUserEx;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.service.AdvisoryRecordingService;
import com.jieshuibao.service.AdvisoryService;
import com.jieshuibao.service.AdvisoryUserService;
import com.jieshuibao.service.CounselorDutyService;
import com.jieshuibao.service.CounselorService;
import com.jieshuibao.service.PushService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.SmsSendService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.WeiXinPayService;
import com.jieshuibao.util.IdGen;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.util.push.PushType;
import com.jieshuibao.wx.po.WxAppPayReq;
import com.jieshuibao.wx.po.WxAppPayRes;
import com.jieshuibao.wx.util.PayCommonUtil;

@Controller
@RequestMapping(value = "/advisory")
public class AdvisoryController {
	private static final Logger logger = LoggerFactory
			.getLogger("AdvisoryController.class");

	private static final ObjectMapper mapper = new ObjectMapper();

	@Resource
	private RedisService redisService;

	@Resource
	private UserService userService;

	@Resource
	private CounselorService counselorService;

	@Resource
	private AdvisoryService advisoryService;

	@Resource
	private WeiXinPayService weiXinPayService;

	@Resource
	private AdvisoryRecordingService advisoryRecordingService;

	@Resource
	private CounselorDutyService counselorDutyService;

	@Resource
	private AdvisoryUserService advisoryUserService;

	@Resource
	private PushService pushService;
	@Resource
	private SmsSendService smsSendService;

	// 咨询支付接口
	@RequestMapping(value = "/buy", method = RequestMethod.POST)
	@ResponseBody
	public Object advisoryBuy(HttpServletRequest request,
			@RequestBody AdvisoryRequest advisoryRequest) {
		HashMap<String, String> map = new HashMap<String, String>();
		try {
			CookieUser cookieUser = (CookieUser) request
					.getAttribute("cookieUser");
			String phoneNum = cookieUser.getPhoneNumber();
			int money = advisoryRequest.getMoney();// 金额
			String payType = advisoryRequest.getPayType();// 支付类型
			String phoneNumber = advisoryRequest.getPhoneNumber();// 用户主键
			if (phoneNumber != null && !phoneNumber.equals("")) {
				User user2 = userService.getUserByPhoneNumber(phoneNumber);
				boolean completeUser = userService.isCompleteUser(phoneNum);
				if (!completeUser) {
					map.put("des", "请完善用户信息");
					map.put("code", BaseRes.ERRORPARAM_CODE);
					return map;
				}
				if (user2 == null) {
					// 手机号错误
					map.put("des", "用户id错误");
					map.put("code", BaseRes.ERRORPARAM_CODE);
					return map;
				}
				if (payType == null || payType.equals("")) {
					map.put("des", "支付方式错误！");
					map.put("code", BaseRes.ERRORPARAM_CODE);
					return map;
				}
				Integer role = user2.getRole();
				// String phone4 = user2.getPhone();

				if (role != 2) {
					// 他已经不是咨询师
					map.put("code", BaseRes.ERRORPARAM_CODE);
					map.put("des", "他已经不是咨询师");
					return map;
				}
				String counselorUuid = user2.getCounselorUuid();
				Counselor counselor = counselorService
						.getCounselorByUuid(counselorUuid);
				if (counselor == null) {
					// 数据格式错误
					map.put("code", BaseRes.ERRORPARAM_CODE);
					map.put("des", "数据格式错误");
					return map;
				}

				Integer consultMoney = counselor.getConsultMoney();
				if (money != consultMoney) {
					// 金额错误
					map.put("code", BaseRes.ERRORPARAM_CODE);
					map.put("des", "金额错误");
					return map;
				}

				int compareTo = phoneNum.compareTo(phoneNumber);

				String phone = compareTo >= 0 ? phoneNum + "_" + phoneNumber
						: phoneNumber + "_" + phoneNum;
				AdvisoryExample advisoryExample = new AdvisoryExample();
				Criteria creater = advisoryExample.createCriteria();
				creater.andOnlyIdEqualTo(phone);
				creater.andTypeEqualTo(Const.ADVISORY_STATUS_0);
				creater.andPayStatusEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
				Criteria createCriteria = advisoryExample.createCriteria();
				createCriteria.andOnlyIdEqualTo(phone);
				createCriteria.andTypeEqualTo(Const.ADVISORY_STATUS_2);
				createCriteria.andPayStatusEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
				advisoryExample.or(createCriteria);
				String uuid = IdGen.uuid();
				
				int i = advisoryService.countAdvisory(advisoryExample);
				if (i == 0) {
					if (payType.equals("weixin")) {
						
						 boolean b = advisoryService.updateAdvisoryBuyVersionTwo(uuid, phoneNum, phoneNumber, money, payType);
						 if (b) {
							 WxAppPayReq wxAppPayReq = new WxAppPayReq();
								wxAppPayReq.setPhone(phoneNum);
								wxAppPayReq.setUnitPrice((double) money);
								wxAppPayReq.setProductName("咨询问题");
								wxAppPayReq.setProductType(Const.ZX);
								wxAppPayReq.setProductId(uuid);
								WxAppPayRes appPay = (WxAppPayRes) weiXinPayService
										.appPay(wxAppPayReq, request);
								// wxAppResponse.setTime(date.getTime());
								return appPay;
						}else {
							map.put("code", BaseRes.FAIL_CODE);
							map.put("des", "支付繁忙，请稍后再试！");
							return map;
						}
						
					} else if (payType.equals("balance")||payType.equals("VipBalance")) {
						double balance=0.0;
						if (payType.equals("balance")) {
							balance = cookieUser.getBalance();
						}else {
							balance =cookieUser.getVipBalance();
						}
						if (balance>=money) {
							 boolean b = advisoryService.updateAdvisoryBuyVersionTwo(uuid, phoneNum, phoneNumber, money, payType);
							 if (b) {
								 map.put("code", BaseRes.SUCCESS_CODE);
								 map.put("des", BaseRes.SUCCESS_DES);
								 return map;
							}else {
								map.put("code", BaseRes.FAIL_CODE);
								map.put("des", "支付繁忙，请稍后再试！");
								return map;
							}
						}else {
							map.put("code", BaseRes.FAIL_CODE);
							map.put("des", "余额不足！");
							return map;
						}
						
					}  else {
						map.put("code",BaseRes.ERRORPARAM_CODE);
						map.put("des", "请更新版本");
						return map;
					}
				} else {
					// 你们俩还有未结束的对话 请到聊天记录中查看
					map.put("code", BaseRes.ERRORPARAM_CODE);
					map.put("des", "你们俩还有未结束的对话 请到聊天记录中查看");
					return map;
				}

			} else {
				// 手机错误
				map.put("code", BaseRes.ERRORPARAM_CODE);
				map.put("des", "手机错误");
				return map;
			}

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", BaseRes.FAIL_CODE);
			map.put("des", BaseRes.FAIL_DES);
		}

		return map;
	}

	// 聊天页面记录接口
	@RequestMapping(value = "/recording", method = RequestMethod.POST)
	@ResponseBody
	public Object advisoryAecording(HttpServletRequest request,
			@RequestBody AdvisoryRequest advisoryRequest) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			logger.warn("接收：" + mapper.writeValueAsString(advisoryRequest));
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {

						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							String phoneNumber = advisoryRequest
									.getPhoneNumber();
							long chatTime = advisoryRequest.getChatTime();
							int updown = advisoryRequest.getUpdown();
							// String phone2 = user.getPhone();

							if (phoneNumber != null && !phoneNumber.equals("")) {
								User user2 = userService
										.getUserByPhoneNumber(phoneNumber);
								if (user2 == null) {
									map.put("code", BaseRes.ERRORPARAM_CODE);
									map.put("des", "没有找到用户");
									return map;
								}

								int compareTo = phoneNum.compareTo(phoneNumber);

								String phone = compareTo >= 0 ? phoneNum + "_"
										+ phoneNumber : phoneNumber + "_"
										+ phoneNum;

								// 消除小红点
								AdvisoryUserExample advisoryUserExample = new AdvisoryUserExample();
								com.jieshuibao.model.db.AdvisoryUserExample.Criteria create = advisoryUserExample
										.createCriteria();
								create.andOnlyIdEqualTo(phone);
								create.andUserOneEqualTo(phoneNum);
								List<AdvisoryUser> list = advisoryUserService
										.getAdvisoryUserByExample(advisoryUserExample);
								if (list != null && list.size() == 1) {
									AdvisoryUser advisoryUser1 = list.get(0);
									String type = advisoryUser1.getType();

									if (type.equals(Const.ADVISORY_USER_TYPE_1)) {
										advisoryUser1.setType(Const.ADVISORY_USER_TYPE_0);
										advisoryUserService
												.updateAdvisoryUser(advisoryUser1);
									}

								} else {
									// 关系数据错误
									map.put("code", BaseRes.ERRORPARAM_CODE);
									map.put("des", "关系数据错误");
									return map;
								}

								AdvisoryRecordingExample advisoryRecordingExample = new AdvisoryRecordingExample();
								advisoryRecordingExample.setPageIndex(0);
								advisoryRecordingExample.setPageSize(5);
								advisoryRecordingExample
										.setOrderByClause("chatTime desc");
								com.jieshuibao.model.db.AdvisoryRecordingExample.Criteria createCriteria = advisoryRecordingExample
										.createCriteria();
								if (chatTime == 0) {
									long currentTimeMillis = System
											.currentTimeMillis();
									createCriteria
											.andChatTimeLessThan(currentTimeMillis);
								} else {
									if (updown == 0) {
										createCriteria
												.andChatTimeLessThan(chatTime);
									} else {
										createCriteria
												.andChatTimeGreaterThan(chatTime);
									}
								}
								createCriteria.andOnlyIdEqualTo(phone);
								List<AdvisoryRecordingUser> advisoryRecordingUsers = advisoryRecordingService
										.getAdvisoryRecordingUsers(advisoryRecordingExample);

								if (advisoryRecordingUsers != null) {
									for (AdvisoryRecordingUser advisoryRecordingUser : advisoryRecordingUsers) {
										String counselorDuty = advisoryRecordingUser
												.getCounselorDuty();
										if (counselorDuty != null
												&& !counselorDuty.equals("")) {
											StringBuilder stringBuilder = new StringBuilder();
											String[] dutys = counselorDuty
													.split(",");
											if (dutys != null) {
												for (String id : dutys) {
													if (id != null
															&& !id.equals("")) {
														Duty duty = counselorDutyService
																.getDutyById(id);
														if (duty != null) {
															stringBuilder
																	.append(duty
																			.getDutyName()
																			+ " ");
														}

													}

												}
												int i = stringBuilder
														.lastIndexOf(" ");
												stringBuilder.delete(i, i + 1);
												advisoryRecordingUser
														.setCounselorDuty(stringBuilder
																.toString());
											}

										}
									}
								}
								Integer role = user2.getRole();
								String otherName=user2.getRealName();
								if (role!=null&&role==Const.USER_ROLE_2) {
									otherName=user2.getUserName();
								}
								map.put("otherName", otherName);//对方用户名
								map.put("code", BaseRes.SUCCESS_CODE);
								map.put("des", "成功");
								map.put("advisoryRecord",
										advisoryRecordingUsers);
								return map;
							} else {
								map.put("code", BaseRes.ERRORPARAM_CODE);
								map.put("des", BaseRes.ERRORPARAM_DES);
								return map;
							}

						} else {
							// 数据格式错误
							map.put("code", BaseRes.RELOGIN_CODE);
							map.put("des", BaseRes.RELOGIN_DES);
							return map;
						}

					} else {
						// 未登录 登陆时间过期
						map.put("code", BaseRes.RELOGIN_CODE);
						map.put("des", BaseRes.RELOGIN_DES);
						return map;
					}
				} else {
					// 未登录
					map.put("code", BaseRes.RELOGIN_CODE);
					map.put("des", BaseRes.RELOGIN_DES);
					return map;
				}

			} else {
				// 未登录
				map.put("code", BaseRes.RELOGIN_CODE);
				map.put("des", BaseRes.RELOGIN_DES);
				return map;
			}

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", BaseRes.FAIL_CODE);
			map.put("des", BaseRes.FAIL_DES);
		}

		return map;
	}

	// 聊天记录

	@RequestMapping(value = "/records", method = RequestMethod.POST)
	@ResponseBody
	public Object advisoryUserList(HttpServletRequest request,
			@RequestBody AdvisoryRequest advisoryRequest) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {

						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							int maxId = advisoryRequest.getMaxId();
							int sinceId = advisoryRequest.getSinceId();
							if (sinceId <= 0) {
								sinceId = 1;
							}
							if (maxId <= 0 || maxId < sinceId) {
								maxId = sinceId;
							}
							AdvisoryUserExample advisoryUserExample = new AdvisoryUserExample();
							advisoryUserExample
									.setOrderByClause("LastTime desc");
							advisoryUserExample.setPageIndex(sinceId - 1);
							advisoryUserExample
									.setPageSize(maxId - sinceId + 1);
							com.jieshuibao.model.db.AdvisoryUserExample.Criteria createCriteria = advisoryUserExample
									.createCriteria();
							createCriteria.andUserOneEqualTo(phoneNum);
							List<AdvisoryUserEx> advisoryUsers = advisoryUserService
									.getAdvisoryUsersByExample(advisoryUserExample);

							map.put("code", BaseRes.SUCCESS_CODE);
							map.put("des", BaseRes.SUCCESS_DES);
							map.put("advisoryUsers", advisoryUsers);
							map.put("maxId", sinceId + advisoryUsers.size() - 1);
							map.put("sinceId", sinceId);
							map.put("rows", advisoryUsers.size());
							return map;
						} else {
							// 数据格式错误
							map.put("code", BaseRes.RELOGIN_CODE);
							map.put("des", BaseRes.RELOGIN_DES);
							return map;
						}

					} else {
						// 未登录 登陆时间过期
						map.put("code", BaseRes.RELOGIN_CODE);
						map.put("des", BaseRes.RELOGIN_DES);
						return map;
					}
				} else {
					// 未登录
					map.put("code", BaseRes.RELOGIN_CODE);
					map.put("des", BaseRes.RELOGIN_DES);
					return map;
				}

			} else {
				// 未登录
				map.put("code", BaseRes.RELOGIN_CODE);
				map.put("des", BaseRes.RELOGIN_DES);
				return map;
			}

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", BaseRes.FAIL_CODE);
			map.put("des", BaseRes.FAIL_DES);
		}

		return map;
	}

	@RequestMapping(value = "/chat", method = RequestMethod.POST)
	@ResponseBody
	public Object advisoryUserChat(HttpServletRequest request,
			@RequestBody AdvisoryRequest advisoryRequest) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {

						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							String uuid = advisoryRequest.getUuid();
							// String onlyId = advisoryRequest.getOnlyId();
							String content = advisoryRequest.getContent();
							String type2 = advisoryRequest.getType();
							if (content == null || content.equals("")) {
								map.put("code", BaseRes.ERRORPARAM_CODE);
								map.put("des", "内容不能为空");
								return map;
							}
							if (type2 == null || type2.equals("")) {
								map.put("code", BaseRes.ERRORPARAM_CODE);
								map.put("des", "消息类型不能为空");
								return map;
							}
							if (uuid != null && !uuid.equals("")) {
								AdvisoryRecording advisoryRecording = advisoryRecordingService
										.getAdvisoryRecordingByUuid(uuid);
								if (advisoryRecording != null) {

									String advisoryId = advisoryRecording
											.getAdvisoryId();
									String onlyId2 = advisoryRecording
											.getOnlyId();
									Advisory advisory = advisoryService
											.getAdvisoryByUuid(advisoryId);
									if (advisory != null) {
										String type = advisory.getType();
										if (!type.equals(Const.ADVISORY_STATUS_0)
												&&!type.equals(Const.ADVISORY_STATUS_2)) {
											map.put("code", BaseRes.ERRORPARAM_CODE);
											map.put("des", "此业务已经结束");
											return map;
										}
										String userRes = advisory.getUserRes();
										String userAsk = advisory.getUserAsk();
										if (phoneNum.equals(userRes)) {
											String string = redisService
													.get(advisoryId + userRes
															+ "_AES");
											if (string == null) {
												// 加推送
												redisService.set(advisoryId
														+ userRes + "_AES",
														"1", 0);
												Set<String> keys = redisService
														.keys("C_" + userAsk
																+ "*");
												if (keys != null) {
													for (String key : keys) {
														CookieUser cookieUserAsk = redisService
																.getObejct(
																		key,
																		CookieUser.class);
														if (cookieUserAsk != null) {
															String realName = user
																	.getPhone();
															String realName2 = user
																	.getRealName();
															if (realName2 != null) {
																realName = realName2;
															}
															pushService
																	.pushAlias(
																			PushType.MODEL_5,
																			new String[] {userRes,realName,userRes},userAsk,PushType.ACTIVITY_1);
															User user2 = userService.getUserByPhoneNumber(userAsk);
															if(user2 != null){
																smsSendService.sendNotify("8aaf07086619653001661b1865b301fa", cookieUserAsk.getPhone(), Const.SCENE_ADVISORY_USER, new String[]{realName});
															}
														}
													}
												}

											} else {

												redisService.incrby(advisoryId
														+ userRes + "_AES");
											}

										}

									} else {
										map.put("code", BaseRes.ERRORPARAM_CODE);
										map.put("des", "此业务id错误");
										return map;
									}
									String type = advisoryRecording.getType();
									if (type != null && !type.equals(Const.ADVISORY_RECORDING_STATUS_4)) {
										if (type.equals(Const.ADVISORY_RECORDING_STATUS_3)) {
											map.put("code", BaseRes.ERRORPARAM_CODE);
											map.put("des",
													"咨询师已经发起结束 ，请选择确定或者取消");
											return map;
										}
										AdvisoryRecording advisoryRecording2 = new AdvisoryRecording();
										String uuid1 = UUIDGenerator.getUUID();
										advisoryRecording2.setUuid(uuid1);
										advisoryRecording2.setType(type2);
										advisoryRecording2
												.setAdvisoryId(advisoryId);
										advisoryRecording2.setContent(content);
										advisoryRecording2.setOnlyId(onlyId2);
										advisoryRecording2.setUserId(phoneNum);
										long currentTimeMillis = System
												.currentTimeMillis();
										advisoryRecording2
												.setChatTime(currentTimeMillis);

										AdvisoryUserExample advisoryUserExample = new AdvisoryUserExample();
										com.jieshuibao.model.db.AdvisoryUserExample.Criteria createCriteria = advisoryUserExample
												.createCriteria();
										createCriteria
												.andOnlyIdEqualTo(onlyId2);
										/*
										 * createCriteria.andUserOneEqualTo(phoneNum
										 * );
										 * 
										 * com.jieshuibao.model.db.
										 * AdvisoryUserExample.Criteria
										 * createCriteria2 =
										 * advisoryUserExample.createCriteria();
										 * createCriteria2
										 * .andOnlyIdEqualTo(onlyId2);
										 * createCriteria2
										 * .andUserOtherEqualTo(phoneNum);
										 * advisoryUserExample
										 * .or(createCriteria2);
										 */
										List<AdvisoryUser> list = advisoryUserService
												.getAdvisoryUserByExample(advisoryUserExample);
										if (list != null && list.size() == 2) {
											AdvisoryUser advisoryUser1 = list
													.get(0);
											AdvisoryUser advisoryUser2 = list
													.get(1);

											String userOne = advisoryUser1
													.getUserOne();
											advisoryUser1
													.setLastTime(currentTimeMillis);
											advisoryUser1.setMessage(content);
											advisoryUser2
													.setLastTime(currentTimeMillis);
											advisoryUser2.setMessage(content);
											if (userOne.equals(phoneNum)) {
												advisoryUser1.setType(Const.ADVISORY_USER_TYPE_0);
												advisoryUser2.setType(Const.ADVISORY_USER_TYPE_1);
											} else {
												advisoryUser1.setType(Const.ADVISORY_USER_TYPE_1);
												advisoryUser2.setType(Const.ADVISORY_USER_TYPE_0);
											}
											advisoryUserService
													.updateAdvisoryUserAndRecording(
															advisoryUser1,
															advisoryUser2,
															advisoryRecording2);
											map.put("code", BaseRes.SUCCESS_CODE);
											map.put("des", "成功");
											return map;
										} else {
											// 关系数据错误
											map.put("code", BaseRes.ERRORPARAM_CODE);
											map.put("des", "关系数据错误");
											return map;
										}

									} else {
										// 此聊天已经结束
										map.put("code", BaseRes.ERRORPARAM_CODE);
										map.put("des", "此聊天已经结束");
										return map;
									}

								} else {
									// 数据格式错误 没有找到流水记录
									map.put("code", BaseRes.ERRORPARAM_CODE);
									map.put("des", "没有找到流水记录");
									return map;
								}

							} else {
								map.put("code", BaseRes.ERRORPARAM_CODE);
								map.put("des", "uuid不能为空");
								return map;

							}
						} else {
							// 数据格式错误
							map.put("code", BaseRes.RELOGIN_CODE);
							map.put("des", BaseRes.RELOGIN_DES);
							return map;
						}

					} else {
						// 未登录 登陆时间过期
						map.put("code", BaseRes.RELOGIN_CODE);
						map.put("des", BaseRes.RELOGIN_DES);
						return map;
					}
				} else {
					// 未登录
					map.put("code", BaseRes.RELOGIN_CODE);
					map.put("des", BaseRes.RELOGIN_DES);
					return map;
				}

			} else {
				// 未登录
				map.put("code", BaseRes.RELOGIN_CODE);
				map.put("des", BaseRes.RELOGIN_DES);
				return map;
			}

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", BaseRes.FAIL_CODE);
			map.put("des", BaseRes.FAIL_DES);
		}

		return map;
	}

	// 外面小红点
	@RequestMapping(value = "/red", method = RequestMethod.POST)
	@ResponseBody
	public Object advisoryUserRedDian(HttpServletRequest request) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {

						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							AdvisoryUserExample advisoryUserExample = new AdvisoryUserExample();
							com.jieshuibao.model.db.AdvisoryUserExample.Criteria createCriteria = advisoryUserExample
									.createCriteria();
							createCriteria.andUserOneEqualTo(phoneNum);
							createCriteria.andTypeEqualTo(Const.ADVISORY_USER_TYPE_1);
							int i = advisoryUserService
									.countAdvisoryUser(advisoryUserExample);
							if (i > 0) {
								map.put("code", BaseRes.SUCCESS_CODE);
								map.put("des", "有红点");
								map.put("type", true);
								return map;
							} else {
								map.put("code", BaseRes.SUCCESS_CODE);
								map.put("des", "无红点");
								map.put("type", false);
								return map;
							}

						} else {
							// 数据格式错误
							map.put("code", BaseRes.RELOGIN_CODE);
							map.put("des", BaseRes.RELOGIN_DES);
							return map;
						}

					} else {
						// 未登录 登陆时间过期
						map.put("code", BaseRes.RELOGIN_CODE);
						map.put("des", BaseRes.RELOGIN_DES);
						return map;
					}
				} else {
					// 未登录
					map.put("code", BaseRes.RELOGIN_CODE);
					map.put("des", BaseRes.RELOGIN_DES);
					return map;
				}

			} else {
				// 未登录
				map.put("code", BaseRes.RELOGIN_CODE);
				map.put("des", BaseRes.RELOGIN_DES);
				return map;
			}

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", BaseRes.FAIL_CODE);
			map.put("des", BaseRes.FAIL_DES);
		}

		return map;
	}

	// 用户点结束
	@RequestMapping(value = "/end", method = RequestMethod.POST)
	@ResponseBody
	public Object endAdvisoryUser(HttpServletRequest request,
			@RequestBody AdvisoryRequest advisoryRequest) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {

						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							String uuid = advisoryRequest.getUuid();
							String endType = advisoryRequest.getEndType();

							AdvisoryRecording advisoryRecording = advisoryRecordingService
									.getAdvisoryRecordingByUuid(uuid);
							if (advisoryRecording != null) {

								String advisoryId = advisoryRecording
										.getAdvisoryId();
								String type = advisoryRecording.getType();
								String onlyId = advisoryRecording.getOnlyId();
								// String userId =
								// advisoryRecording.getUserId();
								if (type != null && type.equals(Const.ADVISORY_RECORDING_STATUS_4)) {
									// 此问题已经结束
									map.put("code", BaseRes.ERRORPARAM_CODE);
									map.put("des", "此问题已经结束");
									return map;
								}

								if (endType == null || endType.equals("")) {
									// 数据错误
									map.put("code", BaseRes.ERRORPARAM_CODE);
									map.put("des", "结束类型不能为空");
									return map;
								}
								Advisory advisory = advisoryService
										.getAdvisoryByUuid(advisoryId);
								if (advisory != null) {

									String userAsk = advisory.getUserAsk();
									String userRes = advisory.getUserRes();
									Integer money = advisory.getMoney();

									String type3 = advisory.getType();

									if (type3.equals(Const.ADVISORY_STATUS_0) || type3.equals(Const.ADVISORY_STATUS_2)) {
										Advisory advisory2 = new Advisory();
										AdvisoryRecording advisoryRecording2 = new AdvisoryRecording();
										String uuid1 = UUIDGenerator.getUUID();
										advisoryRecording2.setUuid(uuid1);
										advisoryRecording2
												.setAdvisoryId(advisoryId);

										// advisoryRecording2.setType("3");
										// advisoryRecording2.setContent("$@@@@$");//发起结束

										advisoryRecording2.setOnlyId(onlyId);
										advisoryRecording2.setUserId(phoneNum);
										long currentTimeMillis = System
												.currentTimeMillis();
										advisoryRecording2
												.setChatTime(currentTimeMillis);

										AdvisoryUser advisoryUser1 = null;
										AdvisoryUser advisoryUser2 = null;
										AdvisoryUserExample advisoryUserExample = new AdvisoryUserExample();
										com.jieshuibao.model.db.AdvisoryUserExample.Criteria createCriteria = advisoryUserExample
												.createCriteria();
										createCriteria.andOnlyIdEqualTo(onlyId);
										/*
										 * createCriteria.andUserOneEqualTo(userAsk
										 * );
										 * createCriteria.andUserOtherEqualTo(
										 * userRes); com.jieshuibao.model.db.
										 * AdvisoryUserExample.Criteria
										 * createCriteria2 =
										 * advisoryUserExample.createCriteria();
										 * /
										 * /createCriteria2.andOnlyIdEqualTo(onlyId
										 * );
										 * createCriteria2.andUserOneEqualTo(userRes
										 * );
										 * createCriteria2.andUserOtherEqualTo
										 * (userAsk);
										 * advisoryUserExample.or(createCriteria2
										 * );
										 */
										List<AdvisoryUser> list = advisoryUserService
												.getAdvisoryUserByExample(advisoryUserExample);
										if (list != null && list.size() == 2) {
											advisoryUser1 = list.get(0);
											advisoryUser2 = list.get(1);
											String userOne = advisoryUser1
													.getUserOne();
											advisoryUser1
													.setLastTime(currentTimeMillis);
											advisoryUser2
													.setLastTime(currentTimeMillis);
											if (userOne.equals(phoneNum)) {
												advisoryUser1.setType(Const.ADVISORY_USER_TYPE_0);
												advisoryUser2.setType(Const.ADVISORY_USER_TYPE_1);
											} else {
												advisoryUser1.setType(Const.ADVISORY_USER_TYPE_1);
												advisoryUser2.setType(Const.ADVISORY_USER_TYPE_0);
											}
										} else {
											map.put("code", BaseRes.ERRORPARAM_CODE);
											map.put("des", "关系数据错误");
											return map;
										}

										if (endType.equals("0")) {

											if (phoneNum.equals(userAsk)) {
												// 直接结束
												advisoryRecording2.setType(Const.ADVISORY_RECORDING_STATUS_4);
												advisoryRecording2
														.setContent("#@@^&@@#");
												advisoryUser1
														.setMessage("#@@^&@@#");
												advisoryUser2
														.setMessage("#@@^&@@#");

												advisory2
														.setEndTime(currentTimeMillis);
												advisory2.setType(Const.ADVISORY_STATUS_1);
												advisory2.setUuid(advisoryId);
												advisoryRecordingService
														.addAdvisoryRecordUser(
																advisoryRecording2,
																advisoryUser1,
																advisoryUser2,
																advisory2,
																userRes, money);
												redisService.delete(advisoryId
														+ "_disagree");
												redisService.delete(advisoryId
														+ userRes + "_AES");
												map.put("code", BaseRes.SUCCESS_CODE);
												map.put("des", "结束");
												map.put("type", Const.ADVISORY_RECORDING_STATUS_4);
												return map;

											} else {
												// 被问者 发起结束

												String string = redisService
														.get(advisoryId
																+ "_disagree");

												if (string != null
														&& string.equals("2")) {
													advisoryRecording2
															.setType(Const.ADVISORY_RECORDING_STATUS_4);
													advisoryRecording2
															.setContent("#@@^&@@#");
													advisoryUser1
															.setMessage("#@@^&@@#");
													advisoryUser2
															.setMessage("#@@^&@@#");
													advisory2
															.setEndTime(currentTimeMillis);
													advisory2.setType(Const.ADVISORY_STATUS_1);
													advisory2
															.setUuid(advisoryId);
													advisoryRecordingService
															.addAdvisoryRecordUser(
																	advisoryRecording2,
																	advisoryUser1,
																	advisoryUser2,
																	advisory2,
																	userRes,
																	money);
													redisService
															.delete(advisoryId
																	+ "_disagree");
													redisService
															.delete(advisoryId
																	+ userRes
																	+ "_AES");
													map.put("code", BaseRes.SUCCESS_CODE);
													map.put("des", "结束");
													return map;

												} else {
													advisoryRecording2
															.setType(Const.ADVISORY_RECORDING_STATUS_3);
													advisoryRecording2
															.setContent("咨询师发起结束");
													advisoryUser1
															.setMessage("咨询师发起结束");
													advisoryUser2
															.setMessage("咨询师发起结束");
													advisory2.setType(Const.ADVISORY_STATUS_2);
													advisory2
															.setUuid(advisoryId);
													advisoryRecordingService
															.addAdvisoryRecordUser(
																	advisoryRecording2,
																	advisoryUser1,
																	advisoryUser2,
																	advisory2,
																	userRes,
																	money);
													redisService.set(advisoryId
															+ "_end", uuid1, 0);
													map.put("code", BaseRes.SUCCESS_CODE);
													map.put("des", "发起结束");
													return map;
												}

											}
										} else if (endType.equals("1")) {
											// 同意结束
											if (phoneNum.equals(userAsk)) {
												advisoryRecording2.setType(Const.ADVISORY_RECORDING_STATUS_4);
												advisoryRecording2
														.setContent("#@@^&@@#");
												advisoryUser1
														.setMessage("#@@^&@@#");
												advisoryUser2
														.setMessage("#@@^&@@#");

												advisory2
														.setEndTime(currentTimeMillis);
												advisory2.setType(Const.ADVISORY_STATUS_1);
												advisory2.setUuid(advisoryId);
												advisoryRecordingService
														.addAdvisoryRecordUser(
																advisoryRecording2,
																advisoryUser1,
																advisoryUser2,
																advisory2,
																userRes, money);
												redisService.delete(advisoryId
														+ "_disagree");
												redisService.delete(advisoryId
														+ "_end");
												redisService.delete(advisoryId
														+ userRes + "_AES");
												map.put("code", BaseRes.SUCCESS_CODE);
												map.put("des", "同意结束");
												map.put("type", Const.ADVISORY_RECORDING_STATUS_4);
												return map;
											} else {
												// 数据错误 只有提问者可以同意结束
												map.put("code", BaseRes.ERRORPARAM_CODE);
												map.put("des",
														"数据错误 只有提问者可以同意结束");
												return map;
											}

										} else if (endType.equals("2")) {
											// 不同意结束
											if (phoneNum.equals(userAsk)) {
												String string = redisService
														.get(advisoryId
																+ "_disagree");

												if (string == null) {
													redisService.set(advisoryId
															+ "_disagree", "1",
															0);
												} else if (!string.equals("2")) {
													redisService
															.incrby(advisoryId
																	+ "_disagree");
												}
												redisService.delete(advisoryId
														+ "_end");
												advisory2.setType(Const.ADVISORY_STATUS_0);
												advisory2.setUuid(advisoryId);
												advisoryRecording2.setType(Const.ADVISORY_RECORDING_STATUS_5);
												advisoryRecording2
														.setContent("不同意结束");// 不同意结束
												advisoryUser1
														.setMessage("不同意结束");
												advisoryUser2
														.setMessage("不同意结束");
												advisoryRecordingService
														.addAdvisoryRecordUser(
																advisoryRecording2,
																advisoryUser1,
																advisoryUser2,
																advisory2,
																userRes, money);
												map.put("code", BaseRes.SUCCESS_CODE);
												map.put("des", "取消成功");
												return map;
											} else {
												// 只有提问者可以不同意结束
												map.put("code", BaseRes.ERRORPARAM_CODE);
												map.put("des", "只有提问者可以不同意结束");
												return map;
											}

										} else {
											// 数据格式错误
											map.put("code", BaseRes.ERRORPARAM_CODE);
											map.put("des", "结束类型错误");
											return map;
										}

									} else {
										// 此业务已经结束
										map.put("code", BaseRes.ERRORPARAM_CODE);
										map.put("des", "此业务已经结束");
										return map;
									}

								} else {
									// 业务id错误
									map.put("code", BaseRes.ERRORPARAM_CODE);
									map.put("des", "业务id错误");
									return map;
								}

							} else {
								// uuid 错误
								map.put("code", BaseRes.ERRORPARAM_CODE);
								map.put("des", "uuid 错误");
								return map;
							}
						} else {
							// 数据格式错误
							map.put("code", BaseRes.RELOGIN_CODE);
							map.put("des", BaseRes.RELOGIN_DES);
							return map;
						}

					} else {
						// 未登录 登陆时间过期
						map.put("code", BaseRes.RELOGIN_CODE);
						map.put("des", BaseRes.RELOGIN_DES);
						return map;
					}
				} else {
					// 未登录
					map.put("code", BaseRes.RELOGIN_CODE);
					map.put("des", BaseRes.RELOGIN_DES);
					return map;
				}

			} else {
				// 未登录
				map.put("code", BaseRes.RELOGIN_CODE);
				map.put("des", BaseRes.RELOGIN_DES);
				return map;
			}

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", BaseRes.FAIL_CODE);
			map.put("des", BaseRes.FAIL_DES);
		}

		return map;
	}

	// 咨询评价
	@RequestMapping(value = "/score", method = RequestMethod.POST)
	@ResponseBody
	public Object advisoryScore(HttpServletRequest request,
			@RequestBody AdvisoryRequest advisoryRequest) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {

						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							String uuid = advisoryRequest.getUuid();
							int score = advisoryRequest.getScore();
							String appraisal = advisoryRequest.getAppraisal();

							if (score > 5) {
								score = 5;
							}
							if (score == 0) {
								score = 1;
							}
							Advisory advisory = advisoryService
									.getAdvisoryByUuid(uuid);
							if (advisory != null) {
								String userRes = advisory.getUserRes();
								if (userRes != null && !userRes.equals("")) {
									Counselor counselor = userService
											.getCounselorByPhoneNumber(userRes);
									if (counselor != null) {
										Integer advScore = counselor
												.getAdvScore();
										counselor.setAdvScore(advScore + score
												- 5);
									}

									Advisory advisory2 = new Advisory();
									advisory2.setUuid(uuid);
									advisory2.setScore(score);
									advisory2.setAppraisal(appraisal);
									advisoryService.updateAdvisoryAndCounselor(
											advisory2, counselor);
									map.put("code", BaseRes.SUCCESS_CODE);
									map.put("des", "评价成功");
									return map;
								} else {
									// 数据错误
									map.put("code", BaseRes.ERRORPARAM_CODE);
									map.put("des", "业务数据错误");
									return map;
								}
							} else {
								map.put("code", BaseRes.ERRORPARAM_CODE);
								map.put("des", "uuid错误");
								return map;
							}
						} else {
							// 数据格式错误
							map.put("code", BaseRes.RELOGIN_CODE);
							map.put("des", BaseRes.RELOGIN_DES);
							return map;
						}

					} else {
						// 未登录 登陆时间过期
						map.put("code", BaseRes.RELOGIN_CODE);
						map.put("des", BaseRes.RELOGIN_DES);
						return map;
					}
				} else {
					// 未登录
					map.put("code", BaseRes.RELOGIN_CODE);
					map.put("des", BaseRes.RELOGIN_DES);
					return map;
				}

			} else {
				// 未登录
				map.put("code", BaseRes.RELOGIN_CODE);
				map.put("des", BaseRes.RELOGIN_DES);
				return map;
			}

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", BaseRes.FAIL_CODE);
			map.put("des", BaseRes.FAIL_DES);
		}

		return map;
	}

	@RequestMapping(value = "/isBuy", method = RequestMethod.POST)
	@ResponseBody
	public Object advisoryIsBuy(HttpServletRequest request,
			@RequestBody AdvisoryRequest advisoryRequest) {
		HashMap<String, String> map = new HashMap<String, String>();
		try {
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							String phoneNumber = advisoryRequest
									.getPhoneNumber();
							// String phone3 = user.getPhone();

							if (phoneNumber != null && !phoneNumber.equals("")) {
								User user2 = userService
										.getUserByPhoneNumber(phoneNumber);
								if (user2 == null) {
									// 手机号错误
									map.put("des", "用户id错误");
									map.put("code", BaseRes.ERRORPARAM_CODE);
									return map;
								}
								// String phone4 = user2.getPhone();

								Integer role = user2.getRole();
								if (role == 2) {
									// Long phone1 = Long.valueOf(phone3);
									// Long phone2 = Long.valueOf(phone4);
									int compareTo = phoneNum
											.compareTo(phoneNumber);

									String phone = compareTo >= 0 ? phoneNum
											+ "_" + phoneNumber : phoneNumber
											+ "_" + phoneNum;
									AdvisoryExample advisoryExample = new AdvisoryExample();
									Criteria creater = advisoryExample
											.createCriteria();
									creater.andOnlyIdEqualTo(phone);
									creater.andPayStatusEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
									creater.andTypeNotEqualTo(Const.ADVISORY_STATUS_1)
											.andTypeNotEqualTo(Const.ADVISORY_STATUS_3).andTypeNotEqualTo(Const.ADVISORY_STATUS_4).andTypeNotEqualTo(Const.ADVISORY_STATUS_5);
									int i = advisoryService
											.countAdvisory(advisoryExample);
									if (i == 0) {
										map.put("code", BaseRes.SUCCESS_CODE);
										map.put("des", "跳支付页面");
										return map;
									} else {
										// 你们俩还有未结束的对话 请到聊天记录中查看
										map.put("code", "4");
										map.put("des", "跳聊天页面");
										return map;
									}
								} else {
									// 他已经不是咨询师
									map.put("code", BaseRes.ERRORPARAM_CODE);
									map.put("des", "他已经不是咨询师");
									return map;
								}

							} else {
								// 手机错误
								map.put("code", BaseRes.ERRORPARAM_CODE);
								map.put("des", "用户id错误！");
								return map;
							}
						} else {
							map.put("code", BaseRes.RELOGIN_CODE);
							map.put("des", BaseRes.RELOGIN_DES);
							return map;
						}

					} else {
						// 未登录 登陆时间过期
						map.put("code", BaseRes.RELOGIN_CODE);
						map.put("des", BaseRes.RELOGIN_DES);
						return map;
					}
				} else {
					// 未登录
					map.put("code", BaseRes.RELOGIN_CODE);
					map.put("des", BaseRes.RELOGIN_DES);
					return map;
				}

			} else {
				// 未登录
				map.put("code", BaseRes.RELOGIN_CODE);
				map.put("des", BaseRes.RELOGIN_DES);
				return map;
			}

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", BaseRes.FAIL_CODE);
			map.put("des", BaseRes.FAIL_DES);
		}

		return map;
	}

}
